﻿using System;
using System.Windows.Forms;
using Awesomium.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace RSuite.Services
{
    public class WebHost : WebControl
    {
        private string startUrl;
        private LocalServiceBase service;

        public WebHost(string startUrl, LocalServiceBase service)
        {
            this.startUrl = startUrl;

            this.service = service;
            this.service.Bind(this);

            base.JSConsoleMessageAdded += new Awesomium.Core.JSConsoleMessageAddedEventHandler(WebHost_JSConsoleMessageAdded);
        }

        void WebHost_JSConsoleMessageAdded(object sender, Awesomium.Core.JSConsoleMessageEventArgs e)
        {
            Trace.WriteLine(e.Message);
        }

        public Form CreateForm()
        {
            base.Dock = DockStyle.Fill;

            var form = new Form();
            form.Controls.Add(this);
            form.Load += new EventHandler(delegate(object sender, EventArgs e)
            {
                this.Navigate(this.startUrl);
            });
            form.Size = new System.Drawing.Size(800, 600);

            return form;
        }

        public void Navigate(string url)
        {
            if (File.Exists(url))
            {
                var path = new FileInfo(url).FullName;
                Awesomium.Core.WebCore.BaseDirectory = path.Remove(path.Length - url.Length);
                base.LoadFile(url);
            }
            else
            {
                base.LoadURL(url);
            }
        }
    }
}